<template>
  <div class="dialog-form">
    <el-form ref="taskRef" :model="form" :rules="rules" label-width="80px">
      <el-row :gutter="36">
        <el-col :span="12">
          <el-form-item label="任务名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入盘点任务名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点日期" prop="dateRange">
            <el-date-picker 
              type="daterange" 
              v-model="form.dateRange" 
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD" 
              start-placeholder="开始日期" 
              end-placeholder="结束日期"
              range-separator="至"
              :disabled-date="handleDisabledDate">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点公司" prop="companyId">
            <el-tree-select
              v-model="form.companyId"
              :data="companyList"
              :render-after-expand="true"
              :props="treeProps"
              node-key="id"
              :default-expanded-keys="expandedKeys"
              @change="companyChange"
              check-strictly
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点部门" prop="departId">
            <el-select v-model="form.departId" placeholder="请选择">
              <el-option
                v-for="item in depart"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                :disabled="item.state == 2"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="盘点人员" prop="userId">
            <el-select v-model="form.userId" placeholder="请选择盘点人员" :disabled="!form.companyId">
              <el-option
                v-for="item in userList"
                :key="item.user_id"
                :label="item.user_name"
                :value="item.user_id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="资产类型" prop="assetType">
            <el-select v-model="form.assetType" placeholder="请选择资产类型">
              <el-option
                  v-for="dict in fixed_assets_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="盘点备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入盘点备注，最多100个字" :maxlength="100" show-word-limit />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="dialog-footer">
      <el-button @click="onCancel">取消</el-button>
      <el-button type="primary" @click="onConfirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { getAssetsInventory, addAssetsInventory, updateAssetsInventory, getSelectData } from "@/api/asset/task"
import { getAllCompanies } from '@/api/company/company'
import { listDepartment } from "@/api/company/department"
const { proxy } = getCurrentInstance()
const { fixed_assets_type, asset_task_status } = proxy.useDict('fixed_assets_type', 'asset_task_status')

const taskRef = ref()
const emits = defineEmits(['cancel', 'confirm'])

const expandedKeys = ref([])
const treeProps = {
  label: 'name',
  disabled: (data, node) => {
    return data.state == 2 || data.check == false
  }
}
const userList = ref([])
const companyList = ref([])
const depart = ref()
const form = ref({
  id: null,
  name: null,
  dateRange:null,
  startDate: null,
  endDate: null,
  companyId: null,
  departId: null,
  userId: null,
  assetType: null,
  remark: null,
})
const rules = {
  name: [
    { required: true, message: "盘点任务名称不能为空", trigger: "blur" }
  ],
  dateRange: [
    { required: true, message: "请选择盘点日期", trigger: "blur" }
  ],
  companyId: [
    { required: true, message: "盘点公司不能为空", trigger: "change" }
  ],
  departId: [
    { required: true, message: "盘点部门不能为空", trigger: "change" }
  ],
  userId: [
    { required: true, message: "盘点人员不能为空", trigger: "change" }
  ],
  assetType: [
    { required: true, message: "资产类型不能为空", trigger: "change" }
  ],
  createTime: [
    { required: true, message: "创建时间不能为空", trigger: "blur" }
  ],
  updateTime: [
    { required: true, message: "更新时间不能为空", trigger: "blur" }
  ]
}

const pageInit = (id) => {
  getCompanyList()
  if (id) {
    getAssetsInventory(id).then(response => {
      form.value = response.data
      form.value.dateRange = [form.value.startDate,form.value.endDate]
      getDepart()
      getUserList()
    })
  }
}

const handleDisabledDate = (date) => {
  date = proxy.parseTime(date, '{y}-{m}-{d}')
  const currentDate = proxy.parseTime(new Date(), '{y}-{m}-{d}')
  return date < currentDate
}

function companyChange() {
  form.value.departId = null
  form.value.userId = null
  getDepart()
  getUserList()
}

/** 公司列表 */
function getCompanyList() {
  getAllCompanies().then(res => {
    companyList.value = res.data || []
  })
}

/** 部门列表 */
function getDepart() {
  const params = {
    pageNum: 1,
    pageSize: 100,
    companyId: form.value.companyId
  }
  listDepartment(params).then(response => {
    depart.value = response.rows
  })
}

/** 获取盘点员列表 */
function getUserList() {
  const params = {
    companyId: form.value.companyId
  }
  getSelectData(params).then(response => {
    userList.value = response.data.user
  })
}

const onCancel = () => {
  emits('cancel')
}

const onConfirm = () => {
  taskRef.value.validate(valid => {
    if (valid) {
      form.value.startDate = form.value.dateRange[0]
      form.value.endDate = form.value.dateRange[1]
      if (form.value.id) {
        updateAssetsInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功")
          emits('confirm')
        })
      } else {
        addAssetsInventory(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功")
          emits('confirm')
        })
      }
    }
  })
}

defineExpose({
  pageInit
})

</script>

<style lang="scss" scoped>

</style>